package test.generator.writer;

import java.util.List;

import test.configuration.ConfigFactory;
import test.domain.Roster;
import test.domain.User;
import test.domain.environment.file.OutFile;
import util.FileManager;

public class FileWriter implements Writer {
	private final int maxFileRow;
	private int fileNumber = 0;
	
	private String outFilePath = "D:\\";
	private String outFileName = "user";
	private String outFileExt = ".xml";
	
	private final FileManager fileManager = new FileManager();
	
	public FileWriter() {
		OutFile outFile = ConfigFactory.getConfiguration().getOutFile();
		this.outFilePath = outFile.getPath();
		this.outFileName = outFile.getName();
		this.outFileExt = outFile.getExt();
		this.maxFileRow = outFile.getMaxFileRow();
	}
	
	@Override
	public void write(List<User> users) {
		StringBuilder sb = new StringBuilder();
		int rows = 0;
		
		for (User user : users) {
			sb.append(this.createUserElement(user));
			
			// If user rows is full, flush to file
			if (++rows >= maxFileRow) {
				rows = 0;
				
				try {
					this.writeFile(sb);	
				}
				catch(Exception e) {
					e.printStackTrace();
					break;
				}
				
				sb = new StringBuilder();
			}
		}
		
		if (!"".equals(sb.toString())) {
			try {
				this.writeFile(sb);
			}
			catch(Exception e) {
				e.printStackTrace();
			}
		}

		System.out.println("User data has been generated.");
	}
	
	private void writeFile(StringBuilder sb) throws Exception {
		String fileName = outFilePath + outFileName + fileNumber++ + outFileExt;
		
		sb.insert(0, "<Openfire>\n");
		sb.append("</Openfire>\n");
		
		fileManager.writeFile(fileName, sb);
		System.out.println(this.fileNumber + "th file has been created.");
	}
	
	private String createUserElement(User user) {
		StringBuilder sb = new StringBuilder();
		
		sb.append("<User>\n");

		sb.append("\t<Username>" + user.getUsername() + "</Username>\n");
		sb.append("\t<Password>" + user.getPlainPassword() + "</Password>\n");
		sb.append("\t<Email>" + user.getEmail() + "</Email>\n");
		sb.append("\t<Name>" + user.getName() + "</Name>\n");
		sb.append("\t<CreationDate>" + user.getCreationDate() + "</CreationDate>\n");
		sb.append("\t<ModifiedDate>" + user.getModifiedDate() + "</ModifiedDate>\n");
		
		// Append rosters
		sb.append("\t<Roster>\n");
		for (Roster roster : user.getRosters()) {
			sb.append("\t\t<Item jid=\"" + roster.getJid() + "\" askstatus=\"" + roster.getAsk() + "\" recvstatus=\"" + roster.getRecv() 
					+ "\" substatus=\"" + roster.getSub() + "\" name=\"" + roster.getNick() + "\">\n");
			sb.append("\t\t\t<Group/>\n");
			sb.append("\t\t</Item>\n");
		}
		sb.append("\t</Roster>\n");
		
		sb.append("</User>\n");
		
		return sb.toString();
	}	
}
